//
//  KSSortGoodsViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/22.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import MJRefresh

/// 分拣
class KSSortGoodsViewController: KSBaseViewController {

    @IBOutlet weak var tableView: UITableView!
    /// 选择页面
    private let chooseView = KSPickerOrderChooseView()
    /// 供货单状态
    private var statusStruct = KSFilterStruct()
    /// 仓库
    private var storageStruct = KSFilterStruct()
    /// 分页
    private var page = 1
    /// 选择订单状态
    private var selectOrderState = ""
    /// 订单列表
    private var orderArray: [KSStorageFjlistPickListModel] = []
    /// 开始时间
    private var startTime = ""
    /// 结束时间
    private var endTime = ""
    /// 仓库ID
    private var storageId = ""
    /// 订单状态
    @IBOutlet weak var statusBtn: UIButton!
    /// 仓库
    @IBOutlet weak var storageBtn: UIButton!
    /// 日期
    @IBOutlet weak var dateBtn: UIButton!
    /// 没有数据显示
    private lazy var notHaveDataExistView: KSNotHaveDataExistView = {
        let view = KSNotHaveDataExistView(frame: CGRect(x: 0, y: 50, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight - 50))
        view.initView(imageName: "Common_ListEmpty", content: "暂无订单")
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "分拣"
        
        self.initView()
        self.initData()
    }
    
    /// 初始化页面
    private func initView() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = KSColor.kColorViewBackground
        
        let nib = UINib(nibName: "KSSupplyOrderTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "KSSupplyOrderTableViewCell")
        
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        self.tableView.mj_footer.isHidden = true
        self.tableView.estimatedRowHeight = 131
        
        self.chooseView.isHidden = true
        self.chooseView.delegate = self
        self.view.addSubview(self.chooseView)
        self.chooseView.snp.makeConstraints { (make) in
            make.top.equalTo(50)
            make.left.right.bottom.equalTo(0)
        }
        
        self.view.addSubview(self.notHaveDataExistView)
        
        self.statusBtn.setIconInRightWithSpacing(spacing: 2)
        self.storageBtn.setIconInRightWithSpacing(spacing: 2)
        self.dateBtn.setIconInRightWithSpacing(spacing: 2)
    }
    
    /// 初始化数据
    private func initData() {
        self.statusStruct.descriptionArray = ["全部", "待分拣","已分拣"]
        self.statusStruct.valueArray = ["", "4", "5"]
        
        self.startLoading()
        self.requestData()
    }
    
    // 状态切换
    @IBAction func switchStatusBtnClick(_ sender: Any) {
        self.switchBtnDefaultSetting()
        self.statusBtn.isSelected = true
        if !self.notHaveDataExistView.isHidden {
            self.view.insertSubview(self.chooseView, aboveSubview: self.notHaveDataExistView)
        }
        self.chooseView.changeDataArray(array: self.statusStruct.descriptionArray, selectRow: self.statusStruct.selectRow)
    }
    
    // 仓库切换
    @IBAction func switchStorageBtnClick(_ sender: Any) {
        self.switchBtnDefaultSetting()
        if !self.notHaveDataExistView.isHidden {
            self.view.insertSubview(self.chooseView, aboveSubview: self.notHaveDataExistView)
        }
        self.storageBtn.isSelected = true
        self.chooseView.changeDataArray(array: self.storageStruct.descriptionArray,selectRow: self.storageStruct.selectRow)
    }
    
    // 日期切换
    @IBAction func switchDateBtnClick(_ sender: Any) {
        self.switchBtnDefaultSetting()
        self.dateBtn.isSelected = true
        let timeView = KSChooseTimeView(frame: self.view.bounds)
        timeView.delegate = self
        self.view.addSubview(timeView)
    }
    
    private func switchBtnDefaultSetting() {
        self.chooseView.isHidden = true
        self.statusBtn.isSelected = false
        self.storageBtn.isSelected = false
        self.dateBtn.isSelected = false
    }
    
    @objc func loadNewData() {
        self.page = 1
        self.requestData()
    }
    
    @objc func loadMoreData() {
        self.page += 1
        self.requestData()
    }
    
    private func requestData() {
        let parameter: [String : Any] = ["order_state" : self.selectOrderState, "page" : self.page, "order_begin_time":self.startTime, "order_end_time":self.endTime, "storage_id": self.storageId]
        self.request.requestIosStorageFjlist(parameters: parameter)
    }
    
    /// KSRequestDelegate
    
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        
        if apiType == KSApiType.KSIosStorageFjlist {
            let orderModel = KSStorageFjlistModel.deserialize(from: result)
            self.analyOrderList(model: (orderModel?.data)!)
        }
    }
    
    override func requestFaile(code: Int, message: String, apiType: KSApiType) {
        super.requestFaile(code: code, message: message, apiType: apiType)
        if apiType == KSApiType.KSIosStorageFjlist {
            if self.page > 1 {
                self.page -= 1
            }
            tableView.mj_header.endRefreshing()
            tableView.mj_footer.endRefreshing()
        }
    }
    
    // 订单解析
    fileprivate func analyOrderList(model: KSStorageFjlistDataModel) {
        if self.page == 1 {
            self.orderArray.removeAll()
            if (model.pick_list)!.count > 0 {
                self.notHaveDataExistView.isHidden = true
                if self.page == 1 {
                    // 添加仓库
                    if self.storageStruct.descriptionArray.count == 0 {
                        for storage in (model.storate_list)! {
                            self.storageStruct.descriptionArray.append(storage.name!)
                            self.storageStruct.valueArray.append(String(describing: storage.id))
                        }
                        self.storageStruct.valueArray.insert("", at: 0)
                        self.storageStruct.descriptionArray.insert("全部", at: 0)
                    }
                }
                
                self.orderArray = (model.pick_list)!
                tableView.mj_footer.isHidden = false
            } else {
                self.notHaveDataExistView.isHidden = false
            }
        } else {
            if (model.pick_list)!.count > 0 {
                self.orderArray = self.orderArray + (model.pick_list)!
                tableView.mj_footer.isHidden = false
            } else {
                if self.page > 1 {
                    self.page -= 1
                }
                
                self.progressHUD.showMessage(text: "没有更多订单")
            }
        }
        
        tableView.reloadData()
        tableView.mj_header.endRefreshing()
        tableView.mj_footer.endRefreshing()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

// MARK: - KSChooseScreenTypeDelegate

extension KSSortGoodsViewController: KSChooseScreenTypeDelegate {
    func chooseScreenType(selectRow: NSInteger) {
        if self.statusBtn.isSelected {
            self.statusStruct.selectRow = selectRow
            self.selectOrderState = self.statusStruct.valueArray[selectRow]
            self.statusBtn.setTitle(self.statusStruct.descriptionArray[selectRow], for: .normal)
            self.statusBtn.setIconInRightWithSpacing(spacing: 2)
            self.statusBtn.isSelected = false
        }
        
        if self.storageBtn.isSelected {
            self.storageStruct.selectRow = selectRow
            self.storageId = self.storageStruct.valueArray[selectRow]
            self.storageBtn.setTitle(self.storageStruct.descriptionArray[selectRow], for: .normal)
            self.storageBtn.setIconInRightWithSpacing(spacing: 2)
            self.storageBtn.isSelected = false
        }
        
        self.startLoading()
        self.requestData()
    }
}

// MARK: - KSCompleteEventDelegate

extension KSSortGoodsViewController: KSCompleteEventDelegate {
    func completeClick(startTime: String, endTime: String) {
        self.startTime = startTime
        self.endTime = endTime
        self.dateBtn.isSelected = false
        self.startLoading()
        self.requestData()
    }
    
    func cancleClick() {
        self.dateBtn.isSelected = false
    }
}

extension KSSortGoodsViewController: UITableViewDelegate, UITableViewDataSource {
    
    // UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.orderArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    // UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 131
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSSupplyOrderTableViewCell", for: indexPath) as! KSSupplyOrderTableViewCell
        cell.setDataWithFjModel(model: orderArray[indexPath.section])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let model = orderArray[indexPath.row]
            let vc = KSStartSortGoodsLoadedViewController()
            vc.orderId = model.pickid!
            self.navigationController?.pushViewController(vc, animated: true)
        } else if indexPath.section == 1 {
            self.navigationController?.pushViewController(KSStartSortGoodsViewController(), animated: true)
        }
    }
}
